package com.controller;

import com.constant.Constant;
import com.entity.Chapter;
import com.entity.Resource;
import com.entity.User;
import com.entity.UserRescource;
import com.github.pagehelper.PageInfo;
import com.service.ChapterService;
import com.service.ResourceService;
import com.service.UserResourceService;
import com.util.AjaxResult;
import com.vo.ResourceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

/**
 * date:2021/5/6
 * description:
 * Author:Stargazer
 * /resource/showRs.do?course_id
 */
@Controller
@RequestMapping("/resource")
public class ResourseController {
    @Autowired
    ResourceService resourceService;

    @Autowired
    ChapterService chapterService;

    @Autowired
    UserResourceService userResourceService;

    /**
     *资源校验方法
     *验证用户积分或金币是否足够
     * 用户信息是放到session中的checkup.do
     */
    @ResponseBody
    @RequestMapping("/checkup.do")
    public AjaxResult checkResource(@RequestParam("resource_id") Integer resourceId,@RequestParam("path") String path,
                                    HttpSession session){
        User user = (User) session.getAttribute(Constant.SESSION_USER);//通过session获取当前的user对象

        AjaxResult ajaxResult = resourceService.checkResourceByIdAndUser(resourceId, user);
        return ajaxResult;
    }

    //加载章节资源mp4视频/resource/showRs.do?resource_id=1
    @RequestMapping("/showRs.do")
    public String showRs(@RequestParam("resource_id") Integer resourceId,HttpSession session){
        //根据resourceId查询资源
        Resource resource = resourceService.findResourceByResourceId(resourceId);
        session.setAttribute("resource",resource);
        return "front/front_courseDetail";
    }

//luo
//luo
@RequestMapping("/findBackResource.do")
@ResponseBody
public AjaxResult findBackResource(HttpServletRequest request, ResourceVo resourceVo){
    Integer pageNo = Integer.valueOf(request.getParameter("pageNo"));
    PageInfo<ResourceVo> info = resourceService.findBackResource(pageNo,resourceVo);
    AjaxResult ajaxResult=new AjaxResult();
    ajaxResult.setObj(info);
    return ajaxResult;
}
    //    /resource/toggleStatus.do'
    @RequestMapping("/toggleStatus.do")
    @ResponseBody
    public Integer toggleStatus(Resource resource){
        resourceService.toggleStatus(resource);
        return 0;
    }

    //    resource/down.do
    @RequestMapping("/down.do")
    @ResponseBody
    public ResponseEntity down(HttpServletRequest request, HttpSession session) throws Exception {

        Integer resourceId=Integer.valueOf(request.getParameter("resourceId"));
        Resource resource=resourceService.down(resourceId);
        String filename=resource.getPath();

        ServletContext context = session.getServletContext();
        String realPath = context.getRealPath("/upload");
        System.out.println(realPath);
        String path = realPath + "/"+filename;


        FileInputStream is = new FileInputStream(path);
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",filename);
        ResponseEntity entity = new ResponseEntity(bytes,headers, HttpStatus.OK);

        return entity;
    }


    @RequestMapping("/play.do")
    public String play(HttpServletRequest request,String path){
        request.getSession().setAttribute("path",path);
        return "/background/back_resourceDetailSet";
    }

    //前台查看资源
    @RequestMapping("/findFrontResource.do")
    @ResponseBody
    public PageInfo<ResourceVo> findBackResource(int pageNo,HttpSession session){
        User sessionUser=(User)session.getAttribute("sessionUser");
        int userId=sessionUser.getId();
        return resourceService.findBackResource(pageNo,userId);
    }

    //前台上传资源（标题不能重复）实现断点续传
    @RequestMapping("/addFrontResource.do")
    @ResponseBody
    public AjaxResult getSize(MultipartFile multiFiles, HttpServletRequest request,
                              HttpSession session, HttpServletResponse response) {
        AjaxResult result = new AjaxResult(true, "", null);
        String re_title = request.getParameter("title");
        int cost_type = Integer.parseInt(request.getParameter("cost_type"));
        int cost_number = Integer.parseInt(request.getParameter("cost_number"));
        int chapter_id = Integer.parseInt(request.getParameter("chapter_id"));
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        long file_size = multiFiles.getSize();
        String filename = multiFiles.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        String file_type = filename.substring(index);
        //判断资源标题是否重复
        if (resourceService.existsTitlt(re_title)>0){
            result.setMsg("标题资源重复");
            result.setSuccess(false);
            return result;
        }
        //查询章节标题
        Chapter chapter=chapterService.findChapterById(chapter_id) ;
        HashMap<String,Object> map=new HashMap<>();//将结果封装在map中
        try {
            Properties properties=new Properties();
            properties.load(this.getClass().getClassLoader().getResourceAsStream("file.properties"));
            String resourcePath=session.getServletContext().getRealPath(properties.getProperty("resourcePath")+chapter.getTitle()+"/"+re_title+"/");
            System.out.println("资源的路径："+resourcePath+filename);
            File path=new File(resourcePath,filename);
            if (!path.exists()){
                map.put("start",0);
            }else {
                map.put("start",path.length());
            }
            map.put("path",resourcePath);
            System.out.println("准备上传path==="+path);
            //将数据加入数据库
            Resource resource=new Resource();
            resource.setTitle(re_title);
            resource.setPath(chapter.getTitle()+"-"+re_title+"/"+filename);//存储资源的相对路径
            resource.setOriginal_name(filename);
            resource.setCost_number(cost_number);
            resource.setChapter_id(chapter_id);
            resource.setCost_type(cost_type);
            resource.setCreate_date(new Date());
            resource.setFile_size(file_size);
            resource.setFile_type(file_type);
            resource.setStatus(Constant.STATUS_ENABLE);//启用
            resource.setUser_id(user.getId());
            resourceService.addResource(resource);
            Integer resource_id=resource.getId();
            UserRescource userRescource=new UserRescource();
            userRescource.setId(user.getId());
            userRescource.setResource(resource);
            userRescource.setCreate_date(new Date());
            userRescource.setUpdate_date(new Date());
            userResourceService.addMyResources(userRescource);
        }catch (IOException e){
            result.setSuccess(false);
            result.setMsg(e.getMessage());
            return result;
        }
        result.setObj(map);
        result.setMsg("资源上传中,请稍等...");
        return result;
    }
    //断点续传
    @RequestMapping("/uploadResources.do")
    @ResponseBody
    public AjaxResult upload(MultipartFile file,HttpServletRequest request,HttpSession session){
        AjaxResult result = new AjaxResult(true, "", null);
        HashMap<String,Object> map=new HashMap<>();
        try {
            String filename = request.getParameter("filename");
            int start = Integer.parseInt(request.getParameter("start"));
            //获取文件存储路径
            int resource_id = Integer.parseInt(request.getParameter("resource_id"));
            map.put("resource_id",resource_id);
            Resource resource = resourceService.findPathById(resource_id);
            String path = resource.getPath();
            Properties properties = new Properties();
            properties.load(this.getClass().getClassLoader().getResourceAsStream("file.properties"));
            path = session.getServletContext().getRealPath(properties.getProperty("resourcePath")+path);
            System.out.println("正在上传========================:"+path);
            int index = path.lastIndexOf("\\");
            String dirpath = path.substring(0, index);
            System.out.println("存储目录："+dirpath);
            File dir=new File(dirpath);
            if(!dir.exists()){
                dir.mkdirs();
            }
            File destFile=new File(dirpath,filename);
            RandomAccessFile rfile=new RandomAccessFile(destFile,"rw");
            rfile.seek(start);
            rfile.write(file.getBytes());
            rfile.close();
            map.put("start",start+file.getSize());//保存下次开始上传的位置
            result.setObj(map);
            result.setMsg("上传中...");
            return result;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("uploadError1:"+e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("uploadError2:"+e.getMessage());
            return result;
        }
    }

    //前台修改资源（标题不能重复）
    @RequestMapping("/modifyFrontResource.do")
    @ResponseBody
    public AjaxResult modifyFrontResource(MultipartFile multiFiles, HttpServletRequest request,
                                          HttpSession session){
        AjaxResult result=new AjaxResult(true,"",null);
        int id = Integer.parseInt(request.getParameter("id"));
        String re_title = request.getParameter("title");
        int cost_type = Integer.parseInt(request.getParameter("cost_type"));
        int cost_number = Integer.parseInt(request.getParameter("cost_number"));
        int chapter_id = Integer.parseInt(request.getParameter("chapter_id"));
        User user = (User)session.getAttribute(Constant.SESSION_USER);
        long file_size = multiFiles.getSize();
        String filename = multiFiles.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        String file_type = filename.substring(index);
//        String contentType = multiFiles.getContentType();
        //判断资源标题是否重复
        if(resourceService.existsTitlt(re_title)>1){
            result.setMsg("资源标题重复！");
            result.setSuccess(false);
            return  result;
        }
        Chapter chapter=chapterService.findChapterById(chapter_id);
        HashMap<String,Object>map=new HashMap<>();
        try {
            Properties properties = new Properties();
            properties.load(this.getClass().getClassLoader().getResourceAsStream("file.properties"));
            String resourcePath = session.getServletContext().getRealPath(properties.getProperty("resourcePath")+chapter.getTitle()+"/"+re_title+"/");
            System.out.println("资源的路径："+resourcePath+filename);
            File path = new File(resourcePath,filename);
            if(!path.exists()){
                map.put("start",0);
            }else{
                map.put("start",path.length());
            }
            map.put("path",resourcePath);
            System.out.println("准备上传 path====="+path);
            //更新数据库信息
            Resource resource=new Resource();
            resource.setId(id);
            resource.setTitle(re_title);
            resource.setPath(chapter.getTitle()+"-"+re_title+"/"+filename);           //存储资源的相对路径
            resource.setOriginal_name(filename);
            resource.setCost_number(cost_number);
            resource.setChapter_id(chapter_id);
            resource.setCost_type(cost_type);
            resource.setCreate_date(new Date());
            resource.setFile_size(file_size);
            resource.setFile_type(file_type);
            resource.setStatus(Constant.STATUS_ENABLE);//启用
            resource.setUser_id(user.getId());
            resourceService.modifyFrontResource(resource);
            Integer resource_id = resource.getId();
            map.put("resource_id",resource_id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg(e.getMessage());
            return result;
        }
        result.setObj(map);
        result.setMsg("资源正在上传,请稍等...");
        return result;
    }

    //前台删除资源
    @RequestMapping("/removeFrontResource.do")
    @ResponseBody
    public AjaxResult removeFrontResource(String id){
        Integer integer=Integer.valueOf(id);
        return resourceService.removeFrontResource(integer);
    }
}

